<?php

namespace App\Http\Middleware;

use App\Models\Chanels;
use App\Models\Configs;
use App\Models\Friends;
use App\Models\Pages;
use Closure;

class HomeConfig
{

    public function handle($request, Closure $next)
    {
        view()->share('chanels',$this->getChanel());//share()，分享数据给所有视图，参数一代表键，参数二代表值
        view()->share('setting',$this->getConfig());
        view()->share('singles',$this->getPage());
        view()->share('friends',$this->getFriend());
        return $next($request);
    }

    /**
     * 返回网站导航
     * @return array
     */
    public function getChanel()
    {
        $chanel = Chanels::where('status',Chanels::STATUS_1)
            ->orderBy('id','asc')
            ->get(['id','title', 'link','target'])
            ->toArray();
        return $chanel;
    }

    /**
     * 返回网站配置
     * @return array
     */
    public function getConfig()
    {
        $config = Configs::where('key','setting')
            ->first()
            ->toArray();
//        dump($config['value']);
        return $config['value'];
    }

    /**
     * 返回网站单页
     * @return array
     */
    public function getPage()
    {
        $pages = Pages::select(['id','title','cateid'])
            ->with(['cate' => function ($query) {
                $query->select(['id','name'])->get();
            }])
            ->get()
            ->toArray();
        $_pages = [];
        foreach ($pages as $page){
            $_pages[$page['cateid']]['name'] = $page['cate']['name'];
            $_pages[$page['cateid']]['child'][] = $page;
        }
//        dump($_pages);
        return $_pages;
    }

    /**
     * 返回网站友情连接
     * @return array
     */
    public function getFriend()
    {
        $friends = Friends::select(['name','link'])
            ->where('status',Friends::STATUS_1)
            ->get()
            ->toArray();
        return $friends;
    }
}
